<?php
    /**
    * Service URL
    * IMPORTANT: change to your service URL !!!
    **/
define('SERVICE_URL', 'http://locify.com.server1.azhosting.sk/nearestCaches/service/');

Header("Pragma: No-cache");
Header("Content-type: text/html; charset=utf-8");



    /**
    * functions for converting coordinates
    */
function latDMtoD($lat_h, $lat_d, $lat_m) {
    $degrees = $lat_d+$lat_m/60;
    if ($lat_h=="S")
    $degrees = $degrees * (-1);
    return $degrees;
}
function lonDMtoD($lon_h, $lon_d, $lon_m) {
    $degrees = $lon_d+$lon_m/60;
    if ($lon_h=="W")
    $degrees = $degrees * (-1);
    return $degrees;
}

    /**
    * parse table with nearest caches
    **/
function parseTable($code) {
    global $position, $response;
    $response = $code;

    $table = array();
    $i = 0;
    while($position = strpos(' '.$response, '<tr')) {
        $allTable = $response;
        $position = 0;
        $tr = parseBetween('<tr bgcolor', '</tr>');
        $tr = substr($tr, (strpos($tr, '>')+1));
        if($i!=0&&$i!=1&&!strpos($tr, 'google_ad')) {
            $table[$i] = array();
            while($position = strpos(' '.$tr, '<td')) {
                $response = $tr;
                $position = 0;
                $td = parseBetween('<td', '</td>');
                $td = substr($td, (strpos($td, '>')+1));

                $table[$i][] = $td;
                $tr = substr($tr, (strpos($tr, '</td>')+5));
            }
        }

        if($i!=0&&$i!=1) $response = substr($allTable, (strpos($allTable, '<tr bgcolor')+11));
        $response = substr($response, (strpos($response, '</tr>')+5));
        $i++;
    }

    return $table;
}

    /**
    * function returns content from $response between $start and $end
    **/
function parseBetween($start, $end)
{
    global $position;
    global $response;

    $position2 = strpos($response, $start, $position);
    $position3 = strpos($response, $end, $position2);
    $position = $position3;
    return substr($response, $position2 +strlen($start), ($position3 - $position2 -strlen($start)));
}

    /**
    * function removes HTML from $text
    **/
function removeHTML($text, $leaveBR) {
    if (!$leaveBR)
    {
        $text = str_replace("<br />","\n",$text);
        $text = str_replace("<br>","\n",$text);
    }
    else
    {
        $text = str_replace("<br />","--BR--",$text);
        $text = str_replace("<br>","--BR--",$text);
        $text = str_replace("</p>","--BR--",$text);
        $text = str_replace("<p>","--BR--",$text);
    }

    //strip html
    $ignore = false;
    $text2 = "";
    for($i=0;$i<strlen($text);$i++) {
        if ($text[$i]=="<") $ignore = true;
        if (!$ignore) $text2 .= $text[$i];
        if ($text[$i]==">") $ignore = false;
    }

    //strip unwanted letters
    $text2 = str_replace("&nbsp;"," ",$text2);
    $text2 = str_replace("&eacute;","é",$text2);
    $text2 = str_replace("&ndash;","-",$text2);
    $text2 = str_replace("&deg;","°",$text2);
    $text2 = str_replace("&middot;",". ",$text2);

    //strip \n and whitespaces
    $text2 = str_replace("\r\n"," ",$text2);
    $text2 = str_replace("\n"," ",$text2);
    $text2 = str_replace("  "," ",$text2);
    if ($leaveBR) {
        $text2 = str_replace("--BR--","<br />",$text2);
    }

    return $text2;
}

function adjustHTML($text)
{
    global $lang;
    //replace images with image links
    $pos = 0;
    $text = ' '.$text;
    while ($pos = stripos($text, '<img', $pos+1))
    {
        $startpos = stripos($text, 'src="',$pos);
        $endpos = strpos($text, '"', $startpos+6);
        $url = substr($text, $startpos+5, $endpos-$startpos-5);
        $endtagpos = strpos($text, '>',$pos);
        $text = str_replace(substr($text, $pos, $endtagpos-$pos+1), '<a href="image.php?url='.$url.'">[ '.$lang['view_image'].' ]</a>', $text);
    }
    //strip some HTML tags
    $text = strip_tags($text, "<br><p><a><b><strong><i><em>");
    //strip \n and whitespaces
    $text = str_replace("\r\n"," ",$text);
    $text = str_replace("\n"," ",$text);
    $text = str_replace("  "," ",$text);
    return $text;
}


    /**
    * Login on geocaching.com
    **/
function login($loginName, $password) {
    $loginName = str_replace("{colon}",":",$loginName);
    $lang = getLang();
    $req = & new HTTP_Request('http://www.geocaching.com/login/default.aspx');
    $req->setMethod(HTTP_REQUEST_METHOD_GET);
    $req->sendRequest();
    $response = $req->getResponseBody();
    $position = strpos($response, '__VIEWSTATE');
    $viewstate = parseBetween('value="', '/>');
    $viewstate = trim(str_replace('"', '', $viewstate));
    $position = strpos($response, '__EVENTVALIDATION');
    $eventvalidation = parseBetween('value="', '/>');
    $eventvalidation = trim(str_replace('"', '', $eventvalidation));
    $req = & new HTTP_Request('http://www.geocaching.com/login/default.aspx');
    $req->setMethod(HTTP_REQUEST_METHOD_POST);
    $req->addPostData('__VIEWSTATE', $viewstate);
    $req->addPostData('__EVENTVALIDATION', $eventvalidation);
	$req->addPostData('ctl00$ContentBody$myUsername', $loginName);
	$req->addPostData('ctl00$ContentBody$myPassword', $password);
	$req->addPostData('ctl00$ContentBody$Button1', 'Login');
    $req->addHeader('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
    $req->sendRequest();
    $cookies = $req->getResponseCookies();
    $cookie = $cookies[0]['value']; 

    if (strpos($req->getResponseBody(), 'does not match') > 0) {
        header($_SERVER["SERVER_PROTOCOL"]." 403 Forbidden");
        echo '<?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                <html>
                  <head>
                    <title>Error</title>
                  </head>
                  <body class="alert">
                    <p class="text">'.$lang['login_failed'].'</p>
                    <a href="'.SERVICE_URL.'search_type.php" class="next">Login</a>
                <locify:timeout value="6000" />
                </body>
                </html>';
        exit;
    } else {
    	header($_SERVER["SERVER_PROTOCOL"]." 202 Accepted");
        if(!isset($_SESSION['cookie'])) $_SESSION['cookie'] = $cookie;
    }
}

    /**
    * Get lang from UserAgent
    **/
function getLang() {
    $agent = explode('/', substr($_SERVER['HTTP_USER_AGENT'], strpos($_SERVER['HTTP_USER_AGENT'], 'Locify')));
    if(strStr($agent[2], ' ')) {
        $foo = explode(' ', $agent[2]);
        $agent[2] = $foo[0];
    }
    if($agent[0] == 'Locify' && isset($agent[2])) {
        $agent[2] = preg_replace('/^([^_]+)_.+$/', '\\1', $agent[2]);
        $lang_file = $agent[2].'.php';
        if(file_exists($lang_file)) {
            require $lang_file;
            return $lang;
        }
    }
    require 'en.php';
    return $lang;
}

    /**
    * Get Locify client version from UserAgent
    **/
function getClientIntVersion()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];
    if(preg_match('/Locify\/((\d+\.)+\d+)\/([a-zA-Z_]{2,6})/', $ua, $match))	{	// client >= 0.7.2
        $clientVersion = $match[1];
    }
    elseif(preg_match('/Locify\/((\d+\.)+\d+)/', $ua, $match))	{	// client = 0.7.1
        $clientVersion = $match[1];
    }
    else	{	// firefox
        $clientVersion = 9.0;
    }

    $version = explode('.', $clientVersion);
    $value = 0;
    switch(count($version))	{
        case 0:
            return 0;
            default:
                $value += min($version[2], 9);
                case 2:
                    $value += min($version[1], 9) * 10;
                    case 1:
                        $value += $version[0] * 100;
                        break;
                }

                return $value;
            }

function convert($stupne, $minuty) {
	$stupne = strtr($stupne, ",", ".");
	$minuty = strtr($minuty, ",", ".");
	if ($stupne > 0) {return $stupne + $minuty/60;}
	else {return $stupne - $minuty/60;}
}
            ?>
